package com.example.testpic;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class AlbumListActivity extends Activity{

	public static List<ImageBucket> dataList;
	private ListView albumListView;
	private AlbumListAdapter albumListAdapter;
	private AlbumHelper albumHelper;
	public static final String EXTRA_IMAGE_LIST = "imagelist";
	public static int imageSelectedTotal = 0;
	public static Map<String, String> map = new HashMap<String, String>();
	public static List<String> pathList = new ArrayList<String>();
	private MediaScannerConnection connection;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pop_list_main);
		connection = new MediaScannerConnection(this, new ImageScannerConnectionClient());
		startScan();
		
		albumHelper = AlbumHelper.getHelper();
		albumHelper.init(getApplicationContext());
		
		dataList = albumHelper.getImagesBucketList(false);
		
		initView();
	}
	
	private void initView() {
		albumListView = (ListView) findViewById(R.id.pop_listview);
		albumListAdapter = new AlbumListAdapter(this, dataList, albumListView);
		albumListView.setAdapter(albumListAdapter);
		albumListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(AlbumListActivity.this,ImageGridActivity.class);
				intent.putExtra(AlbumListActivity.EXTRA_IMAGE_LIST, (Serializable)dataList.get(position).imageList);
				AlbumListActivity.this.startActivity(intent);
				AlbumListActivity.this.finish();
			}
		});
	}

	private void startScan() {
		if (connection.isConnected()) {
			connection.disconnect();
		}
		connection.connect();
	}

	class ImageScannerConnectionClient implements MediaScannerConnectionClient{

		@Override
		public void onMediaScannerConnected() {
			String path = Environment.getExternalStorageDirectory().getAbsolutePath();
			try {
				connection.scanFile(path, "image/*");
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}

		@Override
		public void onScanCompleted(String path, Uri uri) {
		    if (connection.isConnected()) {
		    	connection.disconnect();
			}			
		}
		
	}
}
